package com.zoe.sec02.config;

import com.zoe.sec02.handlere.MyAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @Author Zoe
 * @Date: 2021/03/31
 * @Description
 */
@Configuration
public class SecConfig extends WebSecurityConfigurerAdapter {
    @Resource
    MyAccessDeniedHandler myAccessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
            .loginPage("/login.html")
            .loginProcessingUrl("/login")
            .successForwardUrl("/toMain")
            .failureForwardUrl("/toError");

        // 授权的一些配置。有先后顺序   先定义放行地址  ->  在定义需要认证地址
        http
            .authorizeRequests()
            // 放行login.html地址,多个地址逗号分隔
            .antMatchers("/login.html", "/error.html").permitAll()
            // 放行所有的图片请求
            .antMatchers("/images/**").permitAll()
            // 所有的请求必须要认证后才能访问，必须要登录。
            .anyRequest().authenticated();

        http.csrf().disable();

        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
    }
}
